﻿using log4net;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.Dto;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 理疗服务销售管理 : Form
    {
        private readonly IStockProductBalanceRepository productRepository = new StockProductBalanceRepository();
        private readonly ISalesOrderRepository SalesOrderRepository = new SalesOrderRepository();
        private readonly ISysProductRepository sysProductRepository = new SysProductRepository();
        private readonly ISysUserRepository userReposioty = new SysUserRepository();
        private readonly IMemberInfoRepository MemberInfoReposioty = new MemberInfoRepository();//会员
        private readonly ISalesInfoRepository SalesInfoRepository = new SalesInfoRepository();
        private readonly ISysLogRepository logRepository = new SysLogRepository();
        private readonly IStockProductBalanceRepository productBalanceRepository = new StockProductBalanceRepository();
        private readonly ILog logger = LogManager.GetLogger(nameof(药品销售管理));
        ///单据状态： 制单  已保存

        public 理疗服务销售管理()
        {
            InitializeComponent();
        }

        #region 窗体绘制

        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #endregion 窗体绘制

        private string userId;
        private string userName;

        public 理疗服务销售管理(string userId, string userName)
        {
            InitializeComponent();
            this.userId = userId;
            this.userName = userName;
        }

        #region 取消按钮，默认退出

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion 取消按钮，默认退出

        #region 新增按钮，跳转页面。初始化 订单编号与订单状态

        /// <summary>
        /// 新增按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripAdd_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 1;
            if (dataGridView1.Rows.Count > 0)
            {
                DialogResult RSS = MessageBox.Show(this, "请确保当前订单已经保存成功？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (RSS == DialogResult.Yes)
                {
                    dataGridView1.Rows.Clear();
                }
                else
                {
                    return;
                }
            }
            lab_djbh.Text = "";
            lab_ddzt.Text = "制单";
            toolStripLabel2.Text = "";
            toolStripLabel3.Text = userName;
            Lab_HJcount.Text = "";
            toolStrip1.Text = "";
            toolStripLabel3.Text = "";
            toolStripLabel4.Text = "";
            textBox1.Text = "";
            LAB_id.Text = "";
            textBox1.Select();
        }

        #endregion 新增按钮，跳转页面。初始化 订单编号与订单状态

        #region Load

        private void 采购入库管理_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            lab_djbh.Text = "";
            lab_ddzt.Text = "";
            toolStripLabel3.Text = userName;
            Lab_HJcount.Text = "";
            toolStrip1.Text = "";
            toolStripLabel3.Text = "";
            LAB_id.Text = "";
            textBox1.Text = "";
            this.toolStripLabel4.Margin = new System.Windows.Forms.Padding(this.Width - 700, 1, 0, 2);
            BingOrder();
        }

        #endregion Load

        #region 绑定销售订单

        /// <summary>
        /// 绑定销售单
        /// </summary>
        private void BingOrder()
        {
            dgvSupplyList.AutoGenerateColumns = false;

            StringBuilder where = new StringBuilder();  
            string beginDate = dtpStart.Text;
            string endDate = dtpEnd.Text;
            if (!beginDate.IsNullOrEmpty())
            {
                where.Append($" and CONVERT(VARCHAR,CreateTime,23) >= '{DateTime.Parse(beginDate).ToString("yyyy-MM-dd")}'");
            }
            if (!endDate.IsNullOrEmpty())
            {
                where.Append($" and CONVERT(VARCHAR,CreateTime,23) <= '{DateTime.Parse(endDate).ToString("yyyy-MM-dd")}'");
            }
           var SalesOrderModel = SalesOrderRepository.GetSalesList(where.ToString());

            //var SalesOrderModel = SalesOrderRepository.GetSalesList().Where(m => m.OrderType == 2 ).ToList();
            dgvSupplyList.Rows.Clear();
            for (int i = 0; i < SalesOrderModel.ToList().Count; i++)
            {
                dgvSupplyList.Rows.Add();
                dgvSupplyList.Rows[i].Cells["订单编号"].Value = SalesOrderModel.ToList()[i].OrderCode;
                dgvSupplyList.Rows[i].Cells["制单人"].Value = SalesOrderModel.ToList()[i].UserId;
                dgvSupplyList.Rows[i].Cells["制单时间"].Value = SalesOrderModel.ToList()[i].CreateTime;
                dgvSupplyList.Rows[i].Cells["订单状态"].Value = SalesOrderModel.ToList()[i].State;
                dgvSupplyList.Rows[i].Cells["出库时间"].Value = SalesOrderModel.ToList()[i].ShipTime;
                dgvSupplyList.Rows[i].Cells["订单备注"].Value = SalesOrderModel.ToList()[i].Remark;
                dgvSupplyList.Rows[i].Cells["会员编号"].Value = SalesOrderModel.ToList()[i].MemberId;
                dgvSupplyList.Rows[i].Cells["Id"].Value = SalesOrderModel.ToList()[i].Id;
                dgvSupplyList.Rows[i].Cells["制单人"].Value = SalesOrderModel.ToList()[i].UserName;
                dgvSupplyList.Rows[i].Cells["会员编号"].Value = SalesOrderModel.ToList()[i].MemberName;
                dgvSupplyList.Rows[i].Cells["订单状态"].Value = SalesOrderModel.ToList()[i].State == 0 ? "已送缴费" : "已完成";
                dgvSupplyList.Rows[i].DefaultCellStyle.BackColor = SalesOrderModel.ToList()[i].State == 0 ? Color.GreenYellow : Color.Gray;
                dgvSupplyList.ClearSelection();
            }
        }

        #endregion 绑定销售订单

        #region 绘制订单序号，并且统计总数量与总金额

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            double Money = 0.00;
            double Count = 0;
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
          e.RowBounds.Location.Y,
          dataGridView1.RowHeadersWidth - 4,
          e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            try
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells["金额"].Value != null)
                    {
                        Count++;
                        double num = double.Parse(dataGridView1.Rows[i].Cells["金额"].Value.ToString().Replace("￥", ""));
                        Money += num;
                    }
                }
                Lab_HJcount.Text = "合计：" + Count.ToString() + "笔 ";
                toolStripLabel2.Text = "总金额:￥" + Money.ToString();
            }
            catch (Exception ex)
            {
            }
        }

        #endregion 绘制订单序号，并且统计总数量与总金额

        #region 回车要求填写数量并添加到订单

        /// <summary>按键事件
        /// 药品检索栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView2_KeyDown_1(object sender, KeyEventArgs e)
        {
            //回车
            if (e.KeyCode == Keys.Enter)
            {
                if (lab_ddzt.Text != "制单")
                {
                    MessageBox.Show("此订单已完成,无法更改!");
                    return;
                }
                if (dataGridView2.SelectedRows.Count > 0)
                {
                    string Count;
                    数量 frmNum = new Forms.数量();
                    frmNum.ShowDialog();
                    if (frmNum.DialogResult.Equals(DialogResult.OK))
                    {
                        frmNum.Close();
                        Count = frmNum.Tag.ToString();
                    }
                    else
                    {
                        return;
                    }
                    try
                    {
                        string Id = dataGridView2.SelectedRows[0].Cells["dgv2编号"].Value.ToString();
                        for (int i = 0; i < dataGridView1.Rows.Count; i++)
                        {
                            if (dataGridView1.Rows[i].Cells["药品编码"].Value.ToString() == Id)
                            {
                                MessageBox.Show("已存在该药品");
                                return;
                            }
                        }

                        string name = dataGridView2.SelectedRows[0].Cells["dgv2药品名称"].Value.ToString();
                        string gg = dataGridView2.SelectedRows[0].Cells["dgv2规格"].Value.ToString();
                        string scqy = dataGridView2.SelectedRows[0].Cells["dgv2生产企业"].Value.ToString();
                        string rq = "";
                        string dw = dataGridView2.SelectedRows[0].Cells["dgv2单位"].Value.ToString();
                        string lsj = dataGridView2.SelectedRows[0].Cells["dgv2零售价"].Value.ToString();
                        string hyjzk = dataGridView2.SelectedRows[0].Cells["dgv2会员折扣"].Value.ToString();
                        int index = dataGridView1.Rows.Add();
                        dataGridView1.Rows[index].Cells["药品编码"].Value = Id;
                        dataGridView1.Rows[index].Cells["药品名称"].Value = name;
                        dataGridView1.Rows[index].Cells["规格"].Value = gg;
                        dataGridView1.Rows[index].Cells["生产企业"].Value = scqy;
                        dataGridView1.Rows[index].Cells["单位"].Value = dw;
                        dataGridView1.Rows[index].Cells["零售价"].Value = lsj;
                        string hyj = String.Format("{0:F}", Convert.ToDouble(lsj) * Convert.ToDouble(hyjzk) / 100);
                        dataGridView1.Rows[index].Cells["会员价"].Value = hyj;
                        dataGridView1.Rows[index].Cells["数量"].Value = decimal.Parse(Count);
                        dataGridView1.Rows[index].Cells["金额"].Value = (decimal.Parse(Count) * decimal.Parse(lsj)).ToString();
                        dataGridView1.Rows[index].Cells["会员金额"].Value = (decimal.Parse(Count) * decimal.Parse(hyj)).ToString();
                        dataGridView1.ClearSelection();
                        textBox1.Focus();
                        textBox1.Text = "";
                    }
                    catch (Exception E)
                    {
                    }
                }
            }
        }

        #endregion 回车要求填写数量并添加到订单

        #region 删除订单中的某一项

        #endregion 删除订单中的某一项

        #region 检索药品

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string code = textBox1.Text.Trim();
            //var productList = productRepository.GetStockInfoList(code);
            var productList =
                sysProductRepository.GetProductList($" ProductName LIKE '%{code}%' OR ProductCode LIKE '%{code}%' ");
            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.DataSource = productList;
            dataGridView2.ClearSelection();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (textBox1.Text.Length > 0)
                {
                    if (dataGridView2.Rows.Count > 0)
                    {
                        dataGridView2.Focus();
                        dataGridView2.Rows[0].Selected = true;
                    }
                }
            }
        }

        #endregion 检索药品

        #region 保存订单  (inert  与  update)

        private string 会员ID;
        private string 销售订单备注;

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count <= 0)
            {
                MessageBox.Show("无数据可保存");
                return;
            }

            if (lab_ddzt.Text != "制单")
            {
                MessageBox.Show("此订单已经无法修改!");
                return;
            }
            DialogResult RSS = MessageBox.Show(this, "确定要保存吗，保存之后订单无法修改？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (RSS == DialogResult.No)
            {
                return;
            }
            //会员选择及销售备注页面 frm;

            //if (lab_djbh.Text != "")
            //{
            //    if (lab_ddzt.Text == "已完成")
            //    {
            //        MessageBox.Show("此订单已完成,无法修改!");
            //        return;
            //    }
            //    var SalesOrderModel = SalesOrderRepository.Get(int.Parse(LAB_id.Text));
            //    frm = new 会员选择及销售备注页面(SalesOrderModel.MemberId, SalesOrderModel.Remark);
            //}
            //else
            //{
            //    frm = new 会员选择及销售备注页面();
            //}
            //frm.ShowDialog();

            //if (frm.DialogResult.Equals(DialogResult.OK))
            //{
            //    frm.Close();
            //    string[] info = frm.Tag.ToString().Split('&');
            //    会员ID = info[0].ToString();
            //    销售订单备注 = info[1].ToString();
            //}

            SalesOrder order = new SalesOrder()
            {
                //MemberId = int.Parse(会员ID),
                UserId = this.userId.ToInt(),
                CreateTime = DateTime.Now,
                OrderType = 2,
                Remark = "",// 销售订单备注.Trim(),
                State = 0,
            };
            toolStripLabel4.Text = $"制表时间：{DateTime.Now }";
            List<SalesInfo> infoList = new List<SalesInfo>();
            string dgv_ProductId;
            string dgv_BatchNumber;
            string dgv_Quantity;
            string dgv_Price;
            string dgv_OrderId;
            string dgv_DateExpiry;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dgv_ProductId = dataGridView1.Rows[i].Cells["药品编码"].Value.ToString();
                dgv_Quantity = dataGridView1.Rows[i].Cells["数量"].Value.ToString();
                if (会员ID == "0")
                {
                    dgv_Price = dataGridView1.Rows[i].Cells["零售价"].Value.ToString();
                }
                else
                {
                    dgv_Price = dataGridView1.Rows[i].Cells["会员价"].Value.ToString();
                }

                var info = new SalesInfo();
                info.ProductId = int.Parse(dgv_ProductId);
                info.Quantity = decimal.Parse(dgv_Quantity);
                info.Price = decimal.Parse(dgv_Price);
                if (lab_djbh.Text == "")
                {
                }
                else
                {
                    dgv_OrderId = LAB_id.Text.Trim();
                    info.OrderId = int.Parse(dgv_OrderId);
                }
                infoList.Add(info);
            }
            if (lab_djbh.Text == "")
            {
                int SalesOrderId = SalesOrderRepository.AddSales(order, infoList);
                if (SalesOrderId > 0)
                {
                    LAB_id.Text = SalesOrderId.ToString();
                    var SalesOrderModel = SalesOrderRepository.Get(SalesOrderId);
                    {
                        // 读取销售单号与状态
                        lab_djbh.Text = SalesOrderModel.OrderCode.ToString();
                        if (SalesOrderModel.State == 0)
                        {
                            lab_ddzt.Text = "已送交费";
                        }
                        else
                        {
                            lab_ddzt.Text = "已完成";
                        }
                        MessageBox.Show("已送交费成功！");
                        BingOrder();
                    }
                }
            }
            else//update
            {
                //if (lab_ddzt.Text == "已送交费")
                //{
                //    order.Id = int.Parse(LAB_id.Text);
                //    if (SalesOrderRepository.UpdateSales(order, infoList))
                //    {
                //        MessageBox.Show("更新成功");
                //        BingOrder();
                //    }
                //}
                //else
                {
                    MessageBox.Show("该订单已送交费！无法修改！");
                }
            }
        }

        #endregion 保存订单  (inert  与  update)

        #region 绑定订单明细

        private void dgvSupplyList_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int index = dgvSupplyList.CurrentCell.RowIndex;
                string Id = dgvSupplyList.Rows[index].Cells["Id"].Value.ToString();
                lab_djbh.Text = dgvSupplyList.Rows[index].Cells["订单编号"].Value.ToString();
                lab_ddzt.Text = dgvSupplyList.Rows[index].Cells["订单状态"].Value.ToString();
                LAB_id.Text = Id;
                var SaleOderInfo = SalesOrderRepository.GetSalesInfoList(int.Parse(Id));
                tabControl1.SelectedIndex = 1;
                dataGridView1.Rows.Clear();
                for (int i = 0; i < SaleOderInfo.Count; i++)
                {
                    dataGridView1.Rows.Add();
                    int ypid = SaleOderInfo[i].Id;//药品ID
                    dataGridView1.Rows[i].Cells["药品编码"].Value = SaleOderInfo[i].ProductId;
                    dataGridView1.Rows[i].Cells["药品名称"].Value = SaleOderInfo[i].ProductName;
                    dataGridView1.Rows[i].Cells["规格"].Value = SaleOderInfo[i].Specification;
                    dataGridView1.Rows[i].Cells["单位"].Value = SaleOderInfo[i].MarketingUnit;
                    dataGridView1.Rows[i].Cells["生产企业"].Value = SaleOderInfo[i].ManufacturingEnterprise;
                    dataGridView1.Rows[i].Cells["零售价"].Value = SaleOderInfo[i].RetailPrice;
                    dataGridView1.Rows[i].Cells["会员价"].Value = SaleOderInfo[i].MemberPrice;
                    dataGridView1.Rows[i].Cells["数量"].Value = SaleOderInfo[i].Quantity;
                    dataGridView1.Rows[i].Cells["金额"].Value = (decimal.Parse(SaleOderInfo[i].Quantity.ToString()) * decimal.Parse(SaleOderInfo[i].Price.ToString())).ToString();
                    dataGridView1.Rows[i].Cells["会员金额"].Value = (decimal.Parse(SaleOderInfo[i].Quantity.ToString()) * decimal.Parse(SaleOderInfo[i].MemberPrice.ToString())).ToString();
                    dataGridView1.Rows[i].Cells["药品批号"].Value = SaleOderInfo[i].BatchNumber;
                    dataGridView1.Rows[i].Cells["药品有效期"].Value = SaleOderInfo[i].DateExpiry;
                }
                this.dataGridView1.Refresh();
            }
            catch (Exception w)
            {
            }
        }

        #endregion 绑定订单明细

        #region 解决切换卡顿重影

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int page = tabControl1.SelectedIndex;
            if (page == 0)
            {
                BingOrder();
            }
        }

        #endregion 解决切换卡顿重影

        private void btnCopyOrderCode_Click(object sender, EventArgs e)
        {
            if (lab_djbh.Text.Trim().IsNullOrEmpty())
            {
                MessageBox.Show("暂无订单号");
            }
            else
            {
                Clipboard.SetDataObject(lab_djbh.Text.Trim());
                MessageBox.Show("订单号复制成功");
            }
        }

        private void 设置零售价ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int index = dataGridView1.CurrentCell.RowIndex;
            string money;
            设置价格 price = new 设置价格();
            price.ShowDialog();
            if (price.DialogResult.Equals(DialogResult.OK))
            {
                price.Close();
                money = price.Tag.ToString();
            }
            else
            {
                return;
            }
            try
            {
                ////判断是否低于成本价
                //var product = dataGridView1.Rows[index].Cells["药品编码"].Value.ToString();
                //var list = productBalanceRepository.GetStockBalanceList(" WHERE ProductId = " + product).ToList();
                //if (list[0].CostPrice > decimal.Parse(money))
                //{
                //    MessageBox.Show("销售价不能低于成本价");
                //    return;
                //}
                dataGridView1.Rows[index].Cells["零售价"].Value = money;
                dataGridView1.Rows[index].Cells["金额"].Value = decimal.Parse(money) * decimal.Parse(dataGridView1.Rows[index].Cells["数量"].Value.ToString());
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void 设置会员价ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int index = dataGridView1.CurrentCell.RowIndex;
            string money;
            设置价格 price = new 设置价格();
            price.ShowDialog();
            if (price.DialogResult.Equals(DialogResult.OK))
            {
                price.Close();
                money = price.Tag.ToString();
            }
            else
            {
                return;
            }
            try
            {
                //判断是否低于成本价
                //var product = dataGridView1.Rows[index].Cells["药品编号"].Value.ToString();
                //var list = productBalanceRepository.GetStockBalanceList(" WHERE ProductId = " + product).ToList();
                //if (list[0].CostPrice > decimal.Parse(money))
                //{
                //    MessageBox.Show("销售价不能低于成本价");
                //    return;
                //}
                dataGridView1.Rows[index].Cells["会员价"].Value = money;
                dataGridView1.Rows[index].Cells["会员金额"].Value = decimal.Parse(money) * decimal.Parse(dataGridView1.Rows[index].Cells["数量"].Value.ToString());
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString();
            string orderNum = lab_djbh.Text.Trim();
            string isVip = "普通顾客";
            decimal Moneys = 0.00M;  //总消费金额
            if (lab_ddzt.Text.Trim() == "已完成")
            {
                SalesOrder m = SalesOrderRepository.Get(Convert.ToInt32(LAB_id.Text.Trim()));
                List<SalesInfoDto> saleInfo = SalesOrderRepository.GetSalesInfoList(Convert.ToInt32(LAB_id.Text.Trim()));
                if (saleInfo.Count > 0)
                {
                    string trs = "";
                    foreach (var item in saleInfo)
                    {
                        trs += "<tr>";
                        string pName = item.ProductName;
                        decimal pCount = (decimal)item.Quantity;
                        decimal pPrice = 0.00M;
                        decimal vipMons = 0.00M;
                        if (m.MemberId > 0)
                        {
                            //会员
                            pPrice = item.MemberPrice;  //会员单价
                            vipMons = (decimal.Parse(item.Quantity.ToString()) * decimal.Parse(item.MemberPrice.ToString()));   //会员总金额
                            isVip = "VIP顾客";
                            Moneys += vipMons;
                        }
                        else
                        {
                            pPrice = item.RetailPrice;  //零售价格
                            vipMons = (decimal.Parse(item.Quantity.ToString()) * decimal.Parse(item.RetailPrice.ToString()));  //零售总金额
                            Moneys += vipMons;
                        }

                        trs += "<td>" + pName + "</td><td>" + pPrice + "</td><td>" + pCount + "</td><td>" + Convert.ToDouble(vipMons).ToString("C") + "</td>";
                        trs += "</tr>";
                    }
                    string strHtmlUrl = System.Windows.Forms.Application.StartupPath + "/ticket.html"; //另一种获取方式
                    string strHtml = GetStringByUrl(strHtmlUrl);
                    strHtml = strHtml.Replace("time", time).Replace("orderNum", orderNum).Replace("isVip", isVip).Replace("Moneys", Convert.ToDouble(Moneys).ToString("C")).Replace("trs", trs);
                }
                else
                {
                    MessageBox.Show("无要打印的订单信息");
                }
            }
            else
            {
                MessageBox.Show("请检查订单状态");
            }
        }
        private string GetStringByUrl(string strUrl)
        {
            WebRequest wrt = System.Net.WebRequest.Create(strUrl);
            WebResponse wrse = wrt.GetResponse();
            Stream strM = wrse.GetResponseStream();
            StreamReader SR = new StreamReader(strM, Encoding.UTF8);
            string strallstrm = SR.ReadToEnd();
            return strallstrm;
        }

        private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (textBox1.Text.Length > 0)
                {
                    if (dataGridView2.Rows.Count > 0)
                    {
                        dataGridView2.Focus();
                        dataGridView2.Rows[0].Selected = true;
                    }
                }
            }
        }

        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            string code = textBox1.Text.Trim();
            //var productList = productRepository.GetStockInfoList(code);
            var productList =
                sysProductRepository.GetProductList($" ProductName LIKE '%{code}%' OR ProductCode LIKE '%{code}%' ");
            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.DataSource = productList;
            dataGridView2.ClearSelection();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (lab_ddzt.Text.Contains("制单"))
            {
                try
                {
                    int index = dataGridView1.CurrentCell.RowIndex;
                    DialogResult RSS = MessageBox.Show(this, "确定要删除选中行数据码？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (RSS == DialogResult.Yes)
                    {
                        try
                        {
                            dataGridView1.Rows.RemoveAt(index);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("您还未选中有效行！");
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("您还未选中有效行！");
                }
            }
            else
            {
                MessageBox.Show("此订单状态无法修改!");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BingOrder();
        }
    }
}